<template>
  <Form ref="frmParams" :model="form" :label-width="60">
    <Row :gutter="20">
      <Col span="6">
        <Form.Item label="Host">
          <Select v-model:value="form.env">
            <Select.Option v-for="item of form.envs" :value="item.value">{{ item.name }}</Select.Option>
          </Select>
        </Form.Item>
      </Col>
      <Col span="6" class="btn-group">
        <Button @click="search()" type="primary"><SearchOutlined /> 查询</Button>
        <Button type="default" @click="onCopyResult"><CopyFilled /> 复制结果</Button>
      </Col>
    </Row>
  </Form>
  <Table bordered size="small" :columns="columns" :data-source="datas" :pagination="pagerOption" :scroll="{ y: detailHeight }" @change="search">
    <template #bodyCell="{ column, record }">
      <template v-if="column.key == 'OriginalPageUrl'">
        <Tooltip :title="record.OriginalPageUrl" placement="topLeft" max-width="400">
          <Button type="primary" size="small" shape="round" @click="getOriginalPageUrl(record)" :long="true" target="_blank">访问</Button>
        </Tooltip>
      </template>
      <template v-if="column.key == 'PageUrl'">
        <Tooltip :title="record.PageUrl" placement="topLeft" max-width="400">
          <Button type="default" size="small" :href="record.PageUrl" shape="round" target="_blank">访问</Button>
        </Tooltip>
      </template>
    </template>
  </Table>
</template>
<script setup>
  import md5 from 'js-md5';
  import { useStore } from 'vuex';
  import { ref, reactive, inject, onMounted } from 'vue';
  import { Form, Row, Col, Tooltip, Table, Select, Button } from 'ant-design-vue';
  import { SearchOutlined, CopyFilled } from '@ant-design/icons-vue';

  const $store = useStore();
  const $http = inject('$http');
  const $eventBus = inject('$eventBus');

  const datas = ref([]);
  const detailHeight = ref(430);
  const columns = reactive([
    {
      title: '序号',
      align: 'center',
      width: 70,
      customRender: ({ index }) => (pagerOption.current - 1) * pagerOption.pageSize + index + 1
    },
    { title: '请求页', key: 'OriginalPageUrl', width: 80, align: 'center' },
    { title: '嵌套页', key: 'PageUrl', width: 80, align: 'center' },
    { title: '加载时间', dataIndex: 'LoadedDateTime', width: 180, align: 'center', customRender: ({ record }) => record.LoadedDateTime },
    { title: '加载完成时间', dataIndex: 'CompletedDateTime', width: 180, align: 'center', customRender: ({ record }) => record.CompletedDateTime },
    { title: '耗时(秒)', dataIndex: 'IntervalSeconds' }
  ]);

  const pagerOption = reactive({
    current: 1,
    pageSize: 20,
    defaultPageSize: 20,
    total: 0
  });

  const form = reactive({
    env: 'uat',
    envs: [
      { name: '正式环境', value: 'prod' },
      { name: 'UAT&测试环境', value: 'uat' }
    ]
  });

  function search(pg) {
    let index = 1;

    if (pg) {
      index = pg.current;
      pagerOption.pageSize = pg.pageSize;
    }

    $http.post(`/api/iworkflow/${form.env}/statistics/pageloads`, { pageIndex: index, pageSize: pagerOption.pageSize }).then(rs => {
      datas.value = rs.datas;
      pagerOption.current = index;
      pagerOption.total = rs.total;
    });
  }

  function getOriginalPageUrl(item) {
    let host = 'https://nwf.capitaland.com.cn';

    if (form.env != 'prod') {
      host = 'https://nwfuat.capitaland.com.cn';
    }

    let params = new Map();
    let urls = item.OriginalPageUrl.split('?');
    let queryStrings = (urls[1] || '').split('&');

    queryStrings.forEach(item => {
      let keyValue = item.split('=');

      params.set(keyValue[0], keyValue[1]);
    });

    params.set('UserId', item.UserId);
    params.set('accessUserId', 'dc\\k2dev01');
    params.set('accessUserName', 'k2dev01');
    params.set('timestamp', parseInt(new Date().getTime() / 1000));

    let temp = '';
    let sortedKeys = [...params.keys()].sort((a, b) => a.localeCompare(b));

    sortedKeys.forEach(item => {
      temp += `${item}=${params.get(item)}&`;
    });

    params.set('token', md5(temp.substr(0, temp.length - 1)).toUpperCase());

    let newUrl = urls[0] + '?';

    for (let [key, value] of params) {
      newUrl += `${key}=${value}&`;
    }

    newUrl = newUrl.substr(0, newUrl.length - 1);

    window.open(`${host}${newUrl}`, '_blank');
  }

  function ResizeDetailPanel(area) {
    detailHeight.value = area.height - 172;
  }

  function onCopyResult() {}

  onMounted(() => {
    search();
    let area = $store.state.area.content;

    ResizeDetailPanel(area);

    $eventBus.on('windowResizeChanged', client => ResizeDetailPanel(client));
  });
</script>
